package com.benyanyi.viewbind.listener;

import android.content.pm.PackageManager;
import android.view.View;
import android.widget.Toast;

import java.lang.reflect.Method;

/**
 * @author BenYanYi
 * @date 2018/12/26 10:32
 * @email ben@yanyi.red
 * @overview
 */
public class ViewBindClickListener implements View.OnClickListener {
    private long lastClickTime;
    private Method method;
    private Object object;
    private String netErrorMsg;
    private boolean isCheckNet;
    private boolean isDoubleClick;

    public ViewBindClickListener(Method method, Object object, String netErrorMsg, boolean isCheckNet, boolean isDoubleClick) {
        this.method = method;
        this.object = object;
        this.netErrorMsg = netErrorMsg;
        this.isCheckNet = isCheckNet;
        this.isDoubleClick = isDoubleClick;
    }

    @Override
    public void onClick(View v) {
        long time = System.currentTimeMillis();
        if (isCheckNet) {
            //判断网络问题
            PackageManager pm = v.getContext().getPackageManager();
            boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_NETWORK_STATE", v.getContext().getApplicationContext().getPackageName()));
            if (!permission) {
                Exception exception = new Exception("no android.permission.ACCESS_NETWORK_STATE.");
                exception.printStackTrace();
                return;
            }
            if (!NetUtil.networkAvailable(v.getContext())) {
                Toast.makeText(v.getContext(), netErrorMsg, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (isDoubleClick) {
            long timeD = time - lastClickTime;
            long times = 600;
            if (0 < timeD && timeD < times) {
                return;
            }
        }
        lastClickTime = time;
        method.setAccessible(true);
        try {
            method.invoke(object, v);
        } catch (Exception e) {
            try {
                if (e instanceof IllegalArgumentException) {
                    method.invoke(object);
                } else {
                    method.invoke(object, new Object[]{});
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}
